package top.luqichuang.mycomic.source;

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Request;
import top.luqichuang.common.en.CSourceEnum;
import top.luqichuang.common.json.JsonNode;
import top.luqichuang.common.json.JsonStarter;
import top.luqichuang.common.jsoup.JsoupNode;
import top.luqichuang.common.jsoup.JsoupStarter;
import top.luqichuang.common.model.ChapterInfo;
import top.luqichuang.common.model.Content;
import top.luqichuang.common.util.DecryptUtil;
import top.luqichuang.common.util.NetUtil;
import top.luqichuang.common.util.SourceHelper;
import top.luqichuang.common.util.StringUtil;
import top.luqichuang.mycomic.model.BaseComicSource;
import top.luqichuang.mycomic.model.ComicInfo;

/**
 * @author LuQiChuang
 * @desc
 * @date 2022/7/21 15:17
 * @ver 1.0
 */
public class KuManWu extends BaseComicSource {

    @Override
    public CSourceEnum getSourceEnum() {
        return CSourceEnum.KU_MAN_WU;
    }

    @Override
    public String getIndex() {
        return "http://www.kumwu2.com";
    }

    @Override
    public Request getSearchRequest(String searchString) {
        String url = getIndex() + "/search?keyword=" + searchString;
        return NetUtil.getRequest(url);
    }

    @Override
    public Request buildRequest(String html, String tag, Map<String, Object> data, Map<String, Object> map) {
        if (DETAIL.equals(tag) && map.isEmpty()) {
            if (data.get("oUrl") == null) {
                data.put("oUrl", data.get("url"));
                String id = null;
                try {
                    String url = (String) data.get("url");
                    url = StringUtil.remove(url, getIndex());
                    id = StringUtil.remove(url, "/");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return NetUtil.getRequest(getIndex() + "/chapterlist/" + id + "/");
            } else {
                map.put("moreChapter", html);
                map.put("url", data.get("oUrl"));
                return NetUtil.getRequest((String) data.get("oUrl"));
            }
        }
        return null;
    }

    @Override
    public List<ComicInfo> getInfoList(String html) {
        JsoupStarter<ComicInfo> starter = new JsoupStarter<ComicInfo>() {
            @Override
            protected ComicInfo dealElement(JsoupNode node) {
                String title = node.ownText("p.card-text");
                String author = null;
                String updateTime = null;
                String imgUrl = node.attr("img", "data-src");
                String detailUrl = getIndex() + node.href("a");
                return new ComicInfo(getSourceId(), title, author, detailUrl, imgUrl, updateTime);
            }
        };
        return starter.startElements(html, "section.box li.card");
    }

    @Override
    public void setInfoDetail(ComicInfo info, String html, Map<String, Object> map) {
        JsoupStarter<ChapterInfo> starter = new JsoupStarter<ChapterInfo>() {
            @Override
            protected void dealInfo(JsoupNode node) {
                String title = node.ownText("div.info h1");
                String imgUrl = node.src("div.cover img");
                String author = node.ownText("p.subtitle");
                String intro = node.ownText("p.content");
                String updateStatus = node.ownText("p.tip span span");
                String updateTime = node.ownText("p.tip span:eq(2)");
                author = StringUtil.remove(author, "作者：");
                intro = StringUtil.remove(intro, "漫画简介：");
                updateTime = StringUtil.remove(updateTime, "更新时间：");
                info.setDetail(title, imgUrl, author, updateTime, updateStatus, intro);
            }

            @Override
            protected ChapterInfo dealElement(JsoupNode node) {
                String title = node.ownText("a");
                String chapterUrl = getIndex() + node.href("a");
                return new ChapterInfo(title, chapterUrl);
            }
        };
        List<ChapterInfo> list = starter.startElements(html, "ul.view-win-list li");
        String moreChapter = (String) map.get("moreChapter");
        if (moreChapter != null) {
            JsonStarter<ChapterInfo> jsonStarter = new JsonStarter<ChapterInfo>() {
                @Override
                protected ChapterInfo dealDataList(JsonNode node) {
                    String title = node.string("name");
                    String chapterUrl = map.get("url") + "/" + node.string("id") + ".html";
                    return new ChapterInfo(title, chapterUrl);
                }
            };
            list.addAll(jsonStarter.startDataList(moreChapter, "data", "list"));
        }
        starter.startInfo(html);
        SourceHelper.initChapterInfoList(info, list);
    }

    @Override
    public List<Content> getContentList(String html, int chapterId, Map<String, Object> map) {
        String[] urls = null;
        try {
            String js = StringUtil.matchLast("(eval\\(function.*?\\{\\}\\)\\))", html);
            if (js != null) {
                String[] ss = {"smkhy258", "smkd95fv", "md496952", "cdcsdwq", "vbfsa256", "cawf151c", "cd56cvda", "8kihnt9", "dso15tlo", "5ko6plhy"};
                int dataId = Integer.parseInt(StringUtil.match("data-id=\"(\\d)\"", html));
                String code1 = DecryptUtil.decryptPackedJsCode(js);
                String code2 = ss[dataId];
                code1 = StringUtil.match("=\"(.*?)\"", code1);
                code1 = DecryptUtil.decryptBase64(code1);
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < code1.length(); i++) {
                    builder.append((char) (code1.charAt(i) ^ code2.charAt(i % code2.length())));
                }
                String result = builder.toString();
                result = DecryptUtil.decryptBase64(result);
                if (result != null) {
                    result = result
                            .replace("\"", "")
                            .replace("[", "")
                            .replace("]", "");
                    urls = result.split(",");
                }
            }
        } catch (Exception ignored) {
        }
        return SourceHelper.getContentList(urls, chapterId);
    }

    @Override
    public Map<String, String> getRankMap() {
        String html = "<ul class=\"am-avg-sm-3 am-thumbnails list\"><a href=\"/rank/1-1.html\"><li class=\"am-thumbnail a1 cl-activ\">日阅读榜</li></a><a href=\"/rank/2-1.html\"><li class=\"am-thumbnail a1\">周阅读榜</li></a><a href=\"/rank/3-1.html\"><li class=\"am-thumbnail a1\">月阅读榜</li></a><a href=\"/rank/4-1.html\"><li class=\"am-thumbnail a1\">总阅读榜</li></a><a href=\"/rank/5-1.html\"><li class=\"am-thumbnail a1\">最近更新</li></a><a href=\"/rank/6-1.html\"><li class=\"am-thumbnail a1\">新漫上架</li></a></ul><ul class=\"am-avg-sm-3 am-thumbnails list\"><a href=\"/sort/1-1.html\"><li class=\"am-thumbnail a1 cl-activ\">冒险热血</li></a><a href=\"/sort/2-1.html\"><li class=\"am-thumbnail a1\">武侠格斗</li></a><a href=\"/sort/3-1.html\"><li class=\"am-thumbnail a1\">科幻魔幻</li></a><a href=\"/sort/4-1.html\"><li class=\"am-thumbnail a1\">侦探推理</li></a><a href=\"/sort/5-1.html\"><li class=\"am-thumbnail a1\">耽美爱情</li></a><a href=\"/sort/6-1.html\"><li class=\"am-thumbnail a1\">生活漫画</li></a><a href=\"/sort/11-1.html\"><li class=\"am-thumbnail a1\">推荐漫画</li></a><a href=\"/sort/12-1.html\"><li class=\"am-thumbnail a1\">完结</li></a><a href=\"/sort/13-1.html\"><li class=\"am-thumbnail a1\">连载中</li></a></ul>";
        Map<String, String> map = new LinkedHashMap<>();
        JsoupNode node = new JsoupNode(html);
        Elements elements = node.getElements("a");
        for (Element element : elements) {
            node.init(element);
            map.put(node.ownText("li"), getIndex() + node.href("a"));
        }
        return map;
    }

    @Override
    public List<ComicInfo> getRankInfoList(String html) {
        return getInfoList(html);
    }
}

